import React, { useState } from "react";
import { Modal, Upload, Form, Button } from "antd";
import { fileUpload } from "@/services/common";
import type { UploadProps } from 'antd/es/upload';
import type { UploadFile } from 'antd/es/upload/interface';
import { modalPropsType } from "@/constants/types";
import { PlusOutlined } from "@ant-design/icons";

const {Item} = Form;
const rules = [{required: true, message: '此项必填'}];

const EntrustOrderUpload = ({title, visible, onCancel, onSubmit, loading, currentRow}: modalPropsType) => {
  const [form] = Form.useForm();
  const [fileList, setFileList] = useState<UploadFile[]>([]);

  const normFile = (e: any) => {
    if (Array.isArray(e)) {
      return e;
    }
    return e?.fileList;
  };
  const handleChange: UploadProps['onChange'] = ({ fileList: newFileList }) => setFileList(newFileList);

  const uploadFileReq = ({file, filename, onSuccess, onError, data = {}}: any) => {
    const formData = new FormData();
    formData.append(filename, file);
    Object.keys(data).forEach(key => {
      formData.append(key, data?.[key]);
    })
    fileUpload(formData).then(
      res => {
        if (res?.code === '0') {
          onSuccess(res?.data);
        } else {
          onError(res?.data)
        }
      }
    )
  }

  const handleSubmit = async () => {
    const res = await form.validateFields();
    onSubmit({
      id: currentRow?.id,
      entrustFilePath: res?.entrustFilePath?.[0]?.response,
      entrustFileName: res?.entrustFilePath?.[0]?.response?.split('/')?.pop(),
    });
  }

  return (
    <Modal
      title={title}
      open={visible}
      onCancel={onCancel}
      onOk={handleSubmit}
      confirmLoading={loading}
    >
      <Form form={form} className="modal-form-padding">
      <Item label="委托单" name="entrustFilePath" valuePropName="fileList" getValueFromEvent={normFile} rules={[{required: true, message: '请上传委托单'}]}>
          <Upload 
            maxCount={1} 
            customRequest={uploadFileReq}
            onChange={handleChange}
            fileList={fileList}
            data={{businessCode: 'entrust_file'}} 
          >
            {fileList.length >= 1 ? null : (
              <Button style={{width: 200}} icon={<PlusOutlined />} type="default">上传</Button>
            )}
          </Upload>
        </Item>
      </Form>
    </Modal>
  );
}

export default EntrustOrderUpload;